<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <div class="searchform">
      <el-form
        ref="searchForm"
        :model="search"
        size="mini"
        label-width="90px"
        label-position="right"
      >
        <!--        <el-form-item prop="orgName" label="部门名称">-->
        <!--          <el-input v-model="search.orgName" placeholder="部门名称" />-->
        <!--        </el-form-item>-->
        <el-row :gutter="6">
          <el-col :xs="24" :sm="8" :md="6">
            <el-form-item prop="employeeName" label="员工姓名">
              <el-input v-model="search.employeeName" placeholder="员工姓名" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8" :md="6">
            <el-form-item prop="employeeNo" label="员工编号">
              <el-input v-model="search.employeeNo" placeholder="员工编号" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8" :md="6">
            <el-form-item prop="isOnjob" label="在职状态">
              <r-select
                v-model="search.isOnjob"
                type="1008"
                placeholder="请选择"
                clearable
              />
            </el-form-item>
          </el-col>
          <div style="text-align:right;">
            <el-button type="primary" icon="el-icon-search" @click="searchHandle">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetForm('searchForm')">重置</el-button>
          </div>
        </el-row>
      </el-form>
    </div>
    <!-- 用户列表 -->
    <div class="table">
      <div class="tableHead">
        <div class="tabletitle">员工信息</div>
        <div class="btnGroup">
          <el-button-group>
            <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
          </el-button-group>
        </div>
      </div>
      <BaseTable ref="table" @chaneg-size="changeSizeHandle" @chaneg-page="changePageHandle">
        <el-table-column label="序号" type="index" min-width="50"/>
        <el-table-column align="center" label="操作" min-width="180">
          <template slot-scope="scope">
            <el-tooltip class="item" content="编辑" placement="bottom">
              <el-button
                :disabled="scope.row.IS_ONJOB === '10081002'"
                type="text"
                style="font-size: 20px;"
                icon="el-icon-edit-outline"
                @click="edit(scope.row)"
              />
            </el-tooltip>
            <el-tooltip class="item" content="明细" placement="bottom">
              <el-button
                type="text"
                style="font-size: 20px;"
                icon="el-icon-document"
                @click="detail(scope.row)"
              />
            </el-tooltip>
            <el-tooltip class="item" content="解锁" placement="bottom">
              <el-button
                :disabled="scope.row.LOCK_FLAG === 10041002"
                type="text"
                style="font-size: 20px;"
                icon="el-icon-sold-out"
                @click="removelock(scope.row)"/>
            </el-tooltip>
            <el-tooltip class="item" content="锁定" placement="bottom">
              <el-button :disabled="scope.row.LOCK_FLAG === 10041001 || scope.row.IS_ONJOB === '10081002' || scope.row.USER_CODE === userInfo.dealerCode " type="text" style="font-size: 20px;" icon="el-icon-goods" @click="lock(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="USER_CODE" label="员工帐号" min-width="150"/>
        <el-table-column prop="EMPLOYEE_NO" label="员工编号" min-width="150"/>
        <el-table-column prop="EMPLOYEE_NAME" label="员工姓名" min-width="150"/>
        <el-table-column prop="GENDER" label="性别" min-width="50">
          <template slot-scope="scope">
            <span>{{ scope.row.GENDER | genderFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="ROLE_NAME" label="管理岗位" min-width="100" />
        <el-table-column prop="CERTIFICATE_ID" label="身份证号" min-width="150"/>
        <!--        <el-table-column prop="ORG_NAME" label="部门名称" min-width="120"></el-table-column>-->
        <el-table-column prop="PHONE" label="手机" min-width="120"/>
        <el-table-column prop="IS_ONJOB" label="在职状态" min-width="100">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.IS_ONJOB === 10081001 ? 'success' : 'primary'"
            >{{ scope.row.IS_ONJOB | isonjobFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="LOCK_FLAG" label="是否锁定" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.LOCK_FLAG === 10041001 ? 'success' : 'primary'" close-transition>{{ scope.row.LOCK_FLAG
            | isYESORNO }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="DATA_SOURCES" label="数据来源" min-width="100">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.DATA_SOURCES === 10461001 ? 'success' : 'primary'"
            >{{ scope.row.DATA_SOURCES | datasourcesFilter }}</el-tag>
          </template>
        </el-table-column>
      </BaseTable>
    </div>
    <!-- 弹框 -->
    <el-dialog :title="text" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="75%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px" >
        <el-collapse v-model="mode">
          <el-collapse-item title="员工基本信息" name="1">
            <el-row :gutter="6">
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="员工编号" prop="EMPLOYEE_NO">
                  <el-input v-model="form.EMPLOYEE_NO" disabled placeholder="员工编号" />
                  <el-input v-show="false" v-model="form.EMPLOYEE_ID" placeholder="员工id" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="员工姓名" prop="EMPLOYEE_NAME">
                  <el-input v-model="form.EMPLOYEE_NAME" :disabled="type1 == 'DETAIL' || form.EMPLOYEE_NO === userInfo.dealerCode" placeholder="员工姓名" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="代理商代码" prop="DEALER_CODE" >
                  <el-input v-model="form.DEALER_CODE" placeholder="代理商编码" disabled/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="代理商" prop="DEALER_NAME" >
                  <el-input v-model="form.DEALER_NAME" placeholder="代理商" disabled/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="24" :md="12">
                <!--<el-form-item label="二级代理商" prop="CHILD_DEALER_NAME" >
              <childDealerSelect
                v-model="form.CHILD_DEALER_NAME"
                :dealer-code-in-name="form.CHILD_DEALER_NAME"
                :dealer-dis.sync="dealerDis"
                style="width:160px"
                clearable
                @getChildDealerInfo="getChildDealerInfo"
                @changeCD="changeCD" />
            </el-form-item>
            <el-form-item v-if="false" prop="CHILD_DEALER_CODE">
              <el-input v-model="form.CHILD_DEALER_CODE" />
            </el-form-item>-->
                <!--<el-form-item label="经度" prop="LONGITUDE">
              <el-input v-model="form.LONGITUDE" placeholder="经度"  disabled/>
            </el-form-item>
            <el-form-item label="纬度" prop="LATITUDE">
              <el-input v-model="form.LATITUDE" placeholder="纬度"  disabled/>
            </el-form-item>-->
                <el-form-item :rules="{required: form.EMPLOYEE_NO !== userInfo.dealerCode, message: '必填字段',trigger: 'blur' }" label="岗位" prop="ROLE">
                  <r-select
                    v-model="form.ROLE"
                    :disabled="type1 === 'DETAIL' || form.EMPLOYEE_NO === userInfo.dealerCode"
                    :url="`/basedata/employees/${userInfo.dealerCode}/roles`"
                    selectid="ROLE_ID"
                    selectname="ROLE_NAME"
                    model="DMSCLOUD_BASEDATA"
                    placeholder="请选择"
                    multiple
                  />
                </el-form-item>
              </el-col>
              <!--<el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="学历" prop="EDUCATION">
                  <r-select v-model="form.EDUCATION" :disabled="type1 === 'DETAIL'" type="9015" placeholder="请选择" clearable/>
                </el-form-item>
              </el-col>-->
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="性别" prop="GENDER">
                  <r-select
                    v-model="form.GENDER"
                    :disabled="type1 === 'DETAIL'"
                    type="1002"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="出生日期" prop="BIRTHDAY">
                  <el-date-picker v-model="form.BIRTHDAY" :disabled="type1 === 'DETAIL'" type="date" placeholder="出生日期"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="身份证号" prop="CERTIFICATE_ID">
                  <el-input v-model="form.CERTIFICATE_ID" :disabled="type1 === 'DETAIL'" placeholder="身份证号" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="手机" prop="PHONE">
                  <el-input v-model="form.PHONE" :disabled="type1 === 'DETAIL'" placeholder="手机" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="E_MAIL" prop="E_MAIL">
                  <el-input v-model="form.E_MAIL" :disabled="type1 === 'DETAIL'" placeholder="E_MAIL" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="邮编" prop="ZIP_CODE">
                  <el-input v-model="form.ZIP_CODE" :disabled="type1 === 'DETAIL'" placeholder="邮编" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="在职状态" prop="IS_ONJOB">
                  <el-select
                    v-model="form.IS_ONJOB"
                    :disabled="type1 === 'DETAIL' || form.EMPLOYEE_NO === userInfo.dealerCode"
                    placeholder="请选择"

                    @change="isOnjobChange">
                    <el-option v-for="item in isOnjob" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="离职日期" prop="DIMISSION_DATE">
                  <el-date-picker v-model="form.DIMISSION_DATE" type="date" placeholder="离职日期" disabled/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="建档日期" prop="FOUND_DATE" type="date">
                  <el-date-picker v-model="form.FOUND_DATE" :disabled="type1 !== 'ADD'" type="date" placeholder="建档日期"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="6">
                <el-form-item label="地址" prop="ADDRESS">
                  <el-input v-model="form.ADDRESS" :disabled="type1 === 'DETAIL'" placeholder="地址" />
                </el-form-item>
              </el-col>

            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button v-if="type1 !== 'DETAIL'" type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getJsonTree } from '@/utils/index'
import {
  getUsersList,
  addUserInfo,
  getEmployeeNo,
  getUserInfoById,
  editUserInfo
} from '@/api/admin/org/employeeInfo'
import { removeLockflag, lockflag } from '@/api/admin/auth/employeePermissionInfo'
import BaseTable from '@/components/BaseTable'
import rSelect from '@/components/Select/Select'
import checkbox from '@/components/Checkbox/checkbox'
import filtercode from '@/components/Checkbox/filtercode'
import formMixins from '@/mixins/formMixins'
// import { formatDate } from 'element-ui/packages/date-picker/src/util'
import dealerSelect from '@/views/admin/org/gms/dealerSelect'
import childDealerSelect from './childDealerSelect'
import Gender from '@/components/Select/gender'
import isOnjob from '@/components/Select/isOnjob'
import _ from 'lodash'

import { IDNumber, phone, email, zipCode } from '@/utils/validator'
export default {
  name: 'EmployeeInfo',
  components: {
    BaseTable,
    rSelect,
    checkbox,
    filtercode,
    dealerSelect,
    childDealerSelect,
    Gender,
    isOnjob
  },
  // 过滤器
  filters: {
    isonjobFilter(val) {
      return val === 10081001 ? '在职' : '离职'
    },
    isYESORNO(val) {
      return val === 10041001 ? '是' : '否'
    },
    datasourcesFilter(val) {
      return val === 10461001 ? '店面' : '车厂'
    },
    genderFilter(val) {
      if (val === 10021001) {
        return '男'
      }
      if (val === 10021002) {
        return '女'
      }
      if (val === 10021003) {
        return '未知'
      }
    }
  },
  mixins: [formMixins],
  data() {
    const validateCertificateId = (rule, value, callback) => {
      IDNumber(rule, value, callback)
    }
    return {
      type1: '',
      text: '',
      mode: ['1', '2'],
      form: {
        EMPLOYEE_NO: '',
        EMPLOYEE_NAME: '',
        DEALER_NAME: '',
        CHILD_DEALER_NAME: '',
        LONGITUDE: '',
        LATITUDE: '',
        ROLE: '',
        BIRTHDAY: '',
        GENDER: '',
        CERTIFICATE_ID: '',
        PHONE: '',
        E_MAIL: '',
        ZIP_CODE: '',
        IS_ONJOB: '',
        DIMISSION_DATE: '',
        FOUND_DATE: '',
        ADDRESS: '',
        POSITION_CODE: '',
        EDUCATION: '',
        TECHNICIAN_GRADE: '',
        CHILD_DEALER_CODE: ''

      },
      // 在职状态
      isOnjob: [{
        code: 10081001,
        name: '在职'
      },
      {
        code: 10081002,
        name: '离职'
      }
      ],
      rules: {
        EMPLOYEE_NO: [
          { required: true, message: '请填写员工编号', trigger: 'blur' }
        ],
        EMPLOYEE_NAME: [
          { required: true, message: '请填写员工姓名', trigger: 'blur' }
        ],
        DEALER_NAME: [
          { required: true, message: '请选择代理商', trigger: 'blur' }
        ],
        IS_ONJOB: [{
          required: true,
          message: '请选择在职状态',
          trigger: 'blur'
        }],
        /* ROLE: [
          { required: true, message: '请填写岗位', trigger: 'blur' }
        ],*/
        CERTIFICATE_ID: [
          { required: false, validator: validateCertificateId, trigger: 'blur' }
        ],
        PHONE: [
          { required: true, message: '请填写手机', trigger: 'blur' },
          { trigger: 'blur', validator: phone }
        ],
        // MOBILE: [{ trigger: 'blur', validator: mobilePhone }],
        E_MAIL: [{ trigger: 'blur', validator: email }],
        ZIP_CODE: [{ trigger: 'blur', validator: zipCode }]
      },
      search: {
        limit: 10,
        pageNum: 1,
        employeeName: '',
        orgName: '',
        isOnjob: '',
        employeeNo: ''
      },
      key: '',
      tree: [],
      loading: false,
      dealercode: '',
      dealerName: '',
      dealerDis: false,
      dialogFormVisible: false
    }
  },
  computed: {
    jsonTree() {
      this.tree.forEach(el => (el.label = el.text))
      this.tree.forEach(el => (el.parentId = el.parent))
      return getJsonTree(this.tree)
    },
    ...mapGetters(['userInfo', 'systemParam'])
  },
  mounted() {
    this.searchHandle()
    this.visitDate = new Date()
  },
  methods: {
    searchHandle() {
      const table = this.$refs['table']
      table.wait()
      getUsersList(this.search)
        .then(res => {
          table.complete().filData(res)
        })
        .catch(err => {
          table.complete()
        })
    },
    removelock(data) {
      this.$confirm('是否解锁', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          removeLockflag(data.EMPLOYEE_ID).then(res => {
            this.$message({
              type: 'success',
              message: '解锁成功!'
            })
            this.searchHandle()
          })
            .catch(err => {
            })
        })
        .catch(err => {
          this.$message({
            type: 'info',
            message: '已取消解锁'
          })
        })
    },

    // 锁定
    lock(data) {
      this.$confirm('是否锁定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          lockflag(data.EMPLOYEE_ID).then(res => {
            this.$message({
              type: 'success',
              message: '锁定成功!'
            })
            this.searchHandle()
          })
            .catch(err => {
            })
        })
        .catch(err => {
          this.$message({
            type: 'info',
            message: '已取消锁定'
          })
        })
    },
    getDealerInfo(val) {
      this.$set(this.form, 'DEALER_NAME', val.DEALER_NAME)
      this.dealerCode = val.DEALER_CODE
      this.form.LONGITUDE = val.LONGITUDE
      this.form.LATITUDE = val.LATITUDE
    },
    changeDE() {
      this.form.DEALER_NAME = ''
      this.form.LONGITUDE = ''
      this.form.LATITUDE = ''
    },

    getChildDealerInfo(val) {
      this.$set(this.form, 'CHILD_DEALER_NAME', val.DEALER_NAME)
      this.$set(this.form, 'CHILD_DEALER_CODE', val.DEALER_CODE)
    },
    changeCD() {
      this.form.CHILD_DEALER_NAME = ''
    },
    //
    EmployeeRolesCheck(data) {
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.form = {}
      })
      const id = data.EMPLOYEE_ID
      getUserInfoById(id)
        .then(res => {
          debugger
          // res.forEach(item => {
          this.form = _.cloneDeep(res)
          // })
        })
        .catch(err => {
        })
    },
    // 打开编辑框
    edit(data) {
      this.text = '员工信息编辑'
      this.type1 = 'edit'
      this.dealerDis = false
      this.dialogFormVisible = true
      this.EmployeeRolesCheck(data)
    },
    // 新增
    add() {
      this.type1 = 'add'
      this.text = '员工信息新增'
      this.dealerDis = false
      this.dialogFormVisible = true
      // const params = {
      //   isDealer: true,
      //   dealerCode: this.userInfo.dealerCode,
      //   dealerName: this.userInfo.dealerName
      // }
      /* getDealerSelectList(params)
        .then(res => {
          res.rows.forEach(item => {
            this.$set(this.form, 'LONGITUDE', item.LONGITUDE)
            this.$set(this.form, 'LATITUDE', item.LATITUDE)
          })
        })*/
      getEmployeeNo()
        .then(res => {
          this.$nextTick(() => {
            this.$refs.form.resetFields()
            this.form = {
              DEALER_NAME: this.userInfo.dealerName,
              DEALER_CODE: this.userInfo.dealerCode,
              dealerCode: this.userInfo.dealerCode,
              IS_ONJOB: 10081001,
              FOUND_DATE: new Date(),
              EMPLOYEE_NO: res
            }
          })
        })
    },
    // 明细
    detail(data) {
      this.type1 = 'DETAIL'
      this.text = '员工信息明细'
      this.dealerDis = true
      this.dialogFormVisible = true
      this.EmployeeRolesCheck(data)
    },
    // 弹框确认按钮
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.type1 === 'add') {
            this.addConfirm()
          } else if (this.type1 === 'edit') {
            this.editConfirm()
          }
        } else {
          return false
        }
      })
    },
    // 新增确认
    addConfirm() {
      const params = {
        employeeNo: this.form.EMPLOYEE_NO,
        employeeName: this.form.EMPLOYEE_NAME,
        dealerName: this.form.DEALER_NAME,
        dealerCode: this.dealerCode,
        longitudes: this.form.LONGITUDE,
        latitudes: this.form.LATITUDE,
        role: this.form.ROLE,
        gender: this.form.GENDER,
        birthday: this.form.BIRTHDAY,
        certificateId: this.form.CERTIFICATE_ID,
        phone: this.form.PHONE,
        // mobile: this.form.MOBILE,
        eMail: this.form.E_MAIL,
        zipCode: this.form.ZIP_CODE,
        isOnjob: this.form.IS_ONJOB,
        dimissionDate: this.form.DIMISSION_DATE,
        foundDate: this.form.FOUND_DATE,
        address: this.form.ADDRESS,
        positionCode: this.form.POSITION_CODE,
        education: this.form.EDUCATION,
        technicianGrade: this.form.TECHNICIAN_GRADE,
        childDealerCode: this.form.CHILD_DEALER_CODE
      }
      // if (this.form.LONGITUDE === '' || this.form.LONGITUDE === null ||
      //   this.form.LATITUDE === '' || this.form.LATITUDE === null) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请先维护坐标!'
      //   })
      //   return false
      // } else {
      addUserInfo(params)
        .then(() => {
          this.$message({
            type: 'success',
            message: '员工信息保存成功!'
          })
          this.dialogFormVisible = false
          this.searchHandle()
        })
        .catch(err => {
        })
      // }
    },
    // 修改确认
    editConfirm() {
      const params = {
        employeeNo: this.form.EMPLOYEE_NO,
        employeeName: this.form.EMPLOYEE_NAME,
        dealerName: this.form.DEALER_NAME,
        longitudes: this.form.LONGITUDE,
        latitudes: this.form.LATITUDE,
        role: this.form.ROLE,
        gender: this.form.GENDER,
        birthday: this.form.BIRTHDAY,
        certificateId: this.form.CERTIFICATE_ID,
        phone: this.form.PHONE,
        // mobile: this.form.MOBILE,
        eMail: this.form.E_MAIL,
        zipCode: this.form.ZIP_CODE,
        isOnjob: this.form.IS_ONJOB,
        dimissionDate: this.form.DIMISSION_DATE,
        foundDate: this.form.FOUND_DATE,
        address: this.form.ADDRESS,
        positionCode: this.form.POSITION_CODE,
        education: this.form.EDUCATION,
        technicianGrade: this.form.TECHNICIAN_GRADE,
        childDealerCode: this.form.CHILD_DEALER_CODE
      }
      // if (this.form.LONGITUDE === '' || this.form.LONGITUDE === null ||
      //   this.form.LATITUDE === '' || this.form.LATITUDE === null) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请先维护坐标!'
      //   })
      //   return false
      // } else {
      editUserInfo(params, this.form.EMPLOYEE_ID)
        .then(() => {
          this.$message({
            type: 'success',
            message: '员工信息保存成功!'
          })
          this.dialogFormVisible = false
          this.searchHandle()
        })
        .catch(err => {
        })
      // }
    },
    cancel() {
      this.form = {}
      this.text = ''
      this.type1 = ''
      this.dialogFormVisible = false
    },
    // 在职状态改变事件
    isOnjobChange() {
      if (this.form.IS_ONJOB === 10081002) {
        this.form.DIMISSION_DATE = new Date()
      } else {
        this.form.DIMISSION_DATE = ''
      }
    }
  }
}
</script>

<style scoped>
</style>
